package com.hssy.wululuaplan.service.impl;

import cn.hutool.core.date.DateUtil;
import com.hssy.wululuaplan.entity.InviteCodeRecord;
import com.hssy.wululuaplan.mapper.InviteCodeRecordMapper;
import com.hssy.wululuaplan.service.InviteCodeRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;

/**
 * <p>
 * 邀请码记录 服务实现类
 * </p>
 *
 * @author Mr.Hongtao
 * @since 2025-06-19
 */
@Service
public class InviteCodeRecordServiceImpl extends ServiceImpl<InviteCodeRecordMapper, InviteCodeRecord> implements InviteCodeRecordService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public InviteCodeRecord createInviteCode(Integer userId, Integer expiry) {
        // 根据用户id创建邀请码
        InviteCodeRecord entity = new InviteCodeRecord();
        entity.setUserId(userId);
        entity.setStatus(true);
        // 生成邀请码, 随机6位数字
        String inviteCode = RandomStringUtils.randomNumeric(6);
        entity.setInviteCode(inviteCode);
        // 设置过期时间 默认 1 天
        Date endOfDay = DateUtil.endOfDay(new Date());
        // 将毫秒数清零
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(endOfDay);
        calendar.set(Calendar.MILLISECOND, 0);
        endOfDay = calendar.getTime();

        entity.setExpireTime(DateUtil.offsetDay(endOfDay, expiry == null ? 1 : expiry));
        this.save(entity);
        return entity;
    }
}


